﻿using System;
using System.Linq;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using VSSAHT.Transfer;
using System.Collections.Generic;
using VSS_AHT.DataAccess;
using System.Diagnostics;

namespace VSSAHT.DataAccess
{
    public class ScaleTicketDataAccess : ScaleTicketDataAccessBase, IScaleTicketDataAccess
    {

        private ScaleTicketDTO _searchObject;
        /// <summary>
        /// Search Object Property
        /// </summary>
        public ScaleTicketDTO SearchObject
        {
            get
            {
                return _searchObject;
            }
            set
            {
                if (_searchObject != value)
                {
                    _searchObject = value;
                }
            }
        }

        #region Methods

        public IList<ScaleTicketDTO> Search()
        {
            IList<ScaleTicketDTO> collection = null;
            try
            {
                using (VSSAHTDataContext dataContext = new VSSAHTDataContext(base.ConnectionString))
                {
                    IQueryable<ScaleTicket> query = dataContext.ScaleTickets;
                    if ((_searchObject.OutHour.HasValue) &&  (!String.IsNullOrEmpty(_searchObject.InHour.ToString())))
                    {
                        query = query.Where(e => e.InHour > _searchObject.InHour && e.OutHour < _searchObject.OutHour);
                       
                    }
                    if(!String.IsNullOrEmpty(_searchObject.ScaleTicketCode))
                    {
                        query = query.Where(e=>e.ScaleTicketCode.Contains(_searchObject.ScaleTicketCode));
                    }
                    if (!String.IsNullOrEmpty(_searchObject.VehicleID))
                    {
                        query = query.Where(e => e.VehicleID.Contains(_searchObject.VehicleID));
                    }
                    if (!String.IsNullOrEmpty(_searchObject.ItemName))
                    {
                        query = query.Where(e => e.ItemName.Contains(_searchObject.ItemName));
                    }
                    if (!String.IsNullOrEmpty(_searchObject.CustomerName))
                    {
                        query = query.Where(e => e.CustomerName.Contains(_searchObject.CustomerName));
                    }
                    if (!String.IsNullOrEmpty(_searchObject.LocationCode))
                    {
                        query = query.Where(e => e.LocationCode.Contains(_searchObject.LocationCode));
                    }
                    if (!String.IsNullOrEmpty(_searchObject.RequireName))
                    {
                        query = query.Where(e => e.RequireCode.Contains(_searchObject.RequireName));
                    }

                    collection = new List<ScaleTicketDTO>();
                    foreach (var item in query)
                    {
                        collection.Add(ScaleTicketMapper.ToBusinessObject(item));
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return collection;
        }
        #endregion

        public IList<ScaleTicketDTO> GetList(DateTime fromDate, DateTime toDate, string scaleType, string itemID, string vendorID, string locationID, string requireCode, string vehicleID)
        {
            IList<ScaleTicketDTO> list = null;
            // note: here you can use any persistance library
            // to dynamically populate a list of all objects
            try
            {
                // Process
                using (IDbConnection connection = DbProviderFactory.CreateConnection())
                {
                    connection.ConnectionString = ConnectionString;
                    using (VSSAHTDataContext biocode = new VSSAHTDataContext(connection))
                    {
                        
                        var query = biocode.ScaleTickets.Where(q => q.OutHour >= fromDate.Date && q.OutHour < toDate.Date.AddDays(1) && q.ActualWeight>0);
                        if (!String.IsNullOrEmpty(vendorID))
                            query = query.Where(e => e.CustomerCode.Contains(vendorID) || e.CustomerName.Contains(vendorID));
                        if (!String.IsNullOrEmpty(itemID))
                            query = query.Where(e => e.ItemNumber.Contains(itemID) || e.ItemName.Contains(itemID));
                        if (!String.IsNullOrEmpty(vehicleID))
                            query = query.Where(e => e.VehicleID.Contains(vehicleID));
                        if (!String.IsNullOrEmpty(scaleType))
                            query = query.Where(e => e.ScaleTicketCode.Contains(scaleType));
                        if (!String.IsNullOrEmpty(locationID))
                            query = query.Where(e => e.LocationCode.Contains(locationID) || biocode.Locations.Count(x => x.LocationName.Contains(locationID) && x.LocationCode == e.LocationCode) > 0 );

                        list = query.Select(x => ScaleTicketMapper.ToBusinessObject(x)).ToList();
                        list = list.OrderBy(x => x.InHour).ToList();
                    }
                }
            }
            catch
            {
            }
            return list;
        }

        public IList<ScaleTicketDTO> GetGroupBy(DateTime fromDate, DateTime toDate, string scaleType, string itemID, string vendorID, string locationID, string requireCode, string vehicleID)
        {
            IList<ScaleTicketDTO> list = null;
            // note: here you can use any persistance library
            // to dynamically populate a list of all objects
            try
            {
                // Process
                using (IDbConnection connection = DbProviderFactory.CreateConnection())
                {
                    connection.ConnectionString = ConnectionString;
                    using (VSSAHTDataContext biocode = new VSSAHTDataContext(connection))
                    {

                        var query = biocode.ScaleTickets.Where(q => q.OutHour >= fromDate.Date && q.OutHour < toDate.Date.AddDays(1) && q.ActualWeight > 0);
                        if (!String.IsNullOrEmpty(vendorID))
                            query = query.Where(e => e.CustomerCode.Contains(vendorID) || e.CustomerName.Contains(vendorID));
                        if (!String.IsNullOrEmpty(itemID))
                            query = query.Where(e => e.ItemNumber.Contains(itemID) || e.ItemName.Contains(itemID));
                        if (!String.IsNullOrEmpty(vehicleID))
                            query = query.Where(e => e.VehicleID.Contains(vehicleID));
                        if (!String.IsNullOrEmpty(scaleType))
                            query = query.Where(e => e.ScaleTicketCode.Contains(scaleType));
                        if (!String.IsNullOrEmpty(locationID))
                            query = query.Where(e => e.LocationCode.Contains(locationID) || biocode.Locations.Count(x => x.LocationName.Contains(locationID) && x.LocationCode == e.LocationCode) > 0);

                        list = query.Select(x => ScaleTicketMapper.ToBusinessObject(x)).ToList();
                        list = list.OrderBy(x => x.InHour).ToList();
                    }
                }
            }
            catch
            {
            }
            return list;
        }

        public IList<ScaleTicketDTO> GetList(string workstation, DateTime? date)
        {
            IList<ScaleTicketDTO> list = null;
            // note: here you can use any persistance library
            // to dynamically populate a list of all objects
            try
            {
                // Process
                using (IDbConnection connection = DbProviderFactory.CreateConnection())
                {
                    connection.ConnectionString = ConnectionString;
                    using (VSSAHTDataContext biocode = new VSSAHTDataContext(connection))
                    {
                        string dateKey = String.Empty;
                        if(date.HasValue)
                            dateKey = String.Format("-{0:yyyyMMdd}-", date.Value.Date);
                        // Conditions: in workstation, in date, second weight = 0
                        var query = biocode.ScaleTickets.Where(x => x.ScaleTicketCode.Contains(workstation) && x.ScaleTicketCode.Contains(dateKey) && x.SecondWeight == 0);
                        if (query != null)
                            list = query.Select(e => ScaleTicketMapper.ToBusinessObject(e)).ToList();
                        list = list.OrderBy(x => x.ScaleTicketCode).ToList();
                    }
                }
            }
            catch
            {
            }
            return list;
        }

        public int GetMaxCode(string workstation)
        {
            int code = 1;
            // note: here you can use any persistance library
            // to dynamically populate a list of all objects
            int b = 0;
            int s = 0;
            string temp;
            try
            {
                // Process
                using (IDbConnection connection = DbProviderFactory.CreateConnection())
                {
                    connection.ConnectionString = ConnectionString;
                    using (VSSAHTDataContext biocode = new VSSAHTDataContext(connection))
                    {
                        // <Client>-1|0-20110915-001-R(Nhập)|I(Xuất)|T(Chuyển)
                        string dateKey = String.Format("-{0:yyyyMMdd}-", DateTime.Today);

                       // var maxCode = biocode.ScaleTickets.Where(x => x.ScaleTicketCode.Contains(workstation) && x.ScaleTicketCode.Contains(dateKey)).Max(x => x.ScaleTicketCode.Substring(x.ScaleTicketCode.Length-3,3));
                        
                        var maxCode = biocode.ScaleTickets.Where(x => x.ScaleTicketCode.Contains(workstation) && x.ScaleTicketCode.Contains(dateKey)).Max(x => x.ScaleTicketCode.Substring(x.ScaleTicketCode.IndexOf('-',15)+1,x.ScaleTicketCode.Length -(x.ScaleTicketCode.IndexOf('-',15)+1)));
                        if (maxCode != null)
                        {
                            //string[] part = maxCode.Split('-');
                            //code = Int32.Parse(part[4]) + 1;
                            code = Int32.Parse(maxCode) + 1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return code;
        }
    }
}
